package com.fouram.sentinel.handler;

import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.fouram.core.domain.R;
import com.fouram.core.enums.HttpCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * Sentinel异常处理器
 *
 * @author fouram
 */
@Slf4j
@Order(1)
@RestControllerAdvice
public class SentinelExceptionHandler {

    @Value("${sentinel.msg.flow}")
    private String flowMsg;

    @Value("${sentinel.msg.paramflow}")
    private String paramFlowMsg;

    @Value("${sentinel.msg.degrade}")
    private String degradeMsg;

    @Value("${sentinel.msg.authority}")
    private String authorityMsg;

    /**
     * 权限码异常
     */
    @ExceptionHandler(BlockException.class)
    public R<Void> handleSentinelException(BlockException e) {
        String msg = "未知异常";
        if (e instanceof FlowException) {
            msg = flowMsg;
        } else if (e instanceof ParamFlowException) {
            msg = paramFlowMsg;
        } else if (e instanceof DegradeException) {
            msg = degradeMsg;
        } else if (e instanceof AuthorityException) {
            msg = authorityMsg;
        }
        return R.fail(HttpCodeEnum.FAIL.getCode(), msg);
    }
}